package rejjie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import rejjie.common.R;
import rejjie.dto.DishDto;
import rejjie.dto.SetmealDto;
import rejjie.entity.*;
import rejjie.service.CategoryService;
import rejjie.service.DishService;
import rejjie.service.SetmealDishService;
import rejjie.service.SetmealService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {


    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;
    /**
     * 进行保存时 需要操作多个表， setmeal表 （哪种套餐）和 setmealdish表（套餐内详细的菜品）
     * @param setmealDto
     */
    @PostMapping
    @Transactional
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("{}",setmealDto);
        setmealService.save(setmealDto);


        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        Long id = setmealDto.getId();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(id);
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
        return R.success("成功");
    }


    /**
     * 再setmeal表中进行查询时，我们得到的时categeoryID ，而我们要返回前台的时categeoryname;
     * 所以我们使用的setmealDto 进行数据的回显 因为其中有categoryname;
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<SetmealDto>> pagelist(int page,int pageSize,String name){
        Page<Setmeal> setmealPage = new Page(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page();

        // 构建查询条件
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(name!=null,Setmeal::getName,name);
        lambdaQueryWrapper.orderByAsc(Setmeal::getUpdateTime);
        //进行分页查询
        setmealService.page(setmealPage,lambdaQueryWrapper);


        // 进行元素属性的复制，不复制records,只复制相关分页的记录了
        // 但是因为records中存储的Setmeal的集合，仍然需要进行处理 ，
        // 需要根据 categoryId 得到最终的 categoryName
        BeanUtils.copyProperties(setmealPage,setmealDtoPage);

        List<Setmeal> records = setmealPage.getRecords();

        List<SetmealDto> setmealDtoList= records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            // 对象考培
            BeanUtils.copyProperties(item, setmealDto);

            Long categoryId = item.getCategoryId();
            Category cate = categoryService.getById(categoryId);
            if (cate != null) {
                String name1 = cate.getName();
                setmealDto.setCategoryName(name1);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(setmealDtoList);
        return R.success(setmealDtoPage);

    }

    /**
     * 不光要山出 setmeal表
     * 同时要根绝setmealID删除对应的SetmealDish表中的数据
     * @param ids
     */
   @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
       log.info("{}",ids);
       setmealService.removeWithDish(ids);
       return R.success("套餐删除成功");
   }



    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);
    }


    /**
     *
     * @param id
     * @return
     * 业务流程
     *  根据传过来的setmealId得到  菜品信息
     *  根据套餐id  查询 setmeal_dish表得到我们想要的每个套餐里面有什么菜品List
     * /dish/1584192286153228290
     */
   @GetMapping("/dish/{id}")
    public R<List<DishDto>> getDishlist(@PathVariable Long id){
        log.info("{}",id);
        // 根绝得到的 setmealid 得到套餐里有什么菜品
       LambdaQueryWrapper<SetmealDish> DishFlavorLambdaQueryWrapper = new LambdaQueryWrapper();
       DishFlavorLambdaQueryWrapper.eq(SetmealDish::getSetmealId,id);
       List<SetmealDish> setmealDishes = setmealDishService.list(DishFlavorLambdaQueryWrapper);

       // 根据 得到的 dishid，我们再去 dish表中进行查询 最终返回dish集合
      List<DishDto> dishDtoList = setmealDishes.stream().map((item)->{
          DishDto dishDto = new DishDto();
          BeanUtils.copyProperties(item,dishDto);

          Long dishId = item.getDishId();
          Dish dish  = dishService.getById(dishId);
          BeanUtils.copyProperties(dish,dishDto);

          return dishDto;

       }).collect(Collectors.toList());

      return R.success(dishDtoList);
   }

}
